package com.ihr360.payroll.config;

import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.MigrationInfo;
import org.flywaydb.core.api.MigrationInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;

@RestController
@RequestMapping("/flyway")
public class FlywayController {
    @Value("${flyway.enabled:false}")
    private boolean flywayEnable;

    @Value("${flyway.baseline-on-migrate:false}")
    private boolean flywayBaselineOnMigrate;

    @Value("${flyway.baseline-version:false}")
    private String flywayBaselineVersion;

    @Value("${flyway.locations:classpath:db/migration}")
    private String flywayBaselineLocations;

    @Autowired
    private DataSource dataSource;

    @GetMapping("/migrate")
    public int migrate() {
            Flyway flyway = new Flyway();
            flyway.setDataSource(dataSource);
            flyway.setBaselineVersionAsString(flywayBaselineVersion);
            flyway.setBaselineOnMigrate(flywayBaselineOnMigrate);
            flyway.setLocations(flywayBaselineLocations);
            return flyway.migrate();
    }
    @GetMapping("/validate")
    public void validate() {
        Flyway flyway = new Flyway();
        flyway.setDataSource(dataSource);
        flyway.setBaselineVersionAsString(flywayBaselineVersion);
        flyway.setBaselineOnMigrate(flywayBaselineOnMigrate);
        flyway.setLocations(flywayBaselineLocations);
        flyway.validate();
    }


    @GetMapping("/repair")
    public void repair() {
        Flyway flyway = new Flyway();
        flyway.setDataSource(dataSource);
        flyway.setBaselineVersionAsString(flywayBaselineVersion);
        flyway.setBaselineOnMigrate(flywayBaselineOnMigrate);
        flyway.setLocations(flywayBaselineLocations);
        flyway.repair();
    }

    @GetMapping("/clean")
    public void clean() {
        Flyway flyway = new Flyway();
        flyway.setDataSource(dataSource);
        flyway.setBaselineVersionAsString(flywayBaselineVersion);
        flyway.setBaselineOnMigrate(flywayBaselineOnMigrate);
        flyway.setLocations(flywayBaselineLocations);
        flyway.clean();
    }



    @GetMapping("/info")
    public MigrationInfo[] info() {
        Flyway flyway = new Flyway();
        flyway.setDataSource(dataSource);
        flyway.setBaselineVersionAsString(flywayBaselineVersion);
        flyway.setBaselineOnMigrate(flywayBaselineOnMigrate);
        flyway.setLocations(flywayBaselineLocations);
        MigrationInfoService migrationInfoService=flyway.info();
        return migrationInfoService.all();
    }
}